package com.dream.system.service.impl;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.dream.common.Common;
import com.dream.common.DateTools;
import com.dream.common.SuperDao;
import com.dream.model.SysUser;
import com.dream.model.Sys_Class;
import com.dream.model.Sys_Question;
import com.dream.model.Sys_TestPaper;
import com.dream.model.Sys_User_Question;
import com.dream.model.Sys_User_TestPaper;
import com.dream.system.service.ISys_TestPaper;

@Component("sys_TestPaperServiceImpl")
@SuppressWarnings("all")
public class Sys_TestPaperServiceImpl extends SuperDao<Object> implements ISys_TestPaper {

	/**
	 * 增加一个卷子
	 */
	@Override
	public int addTestPaper(Sys_TestPaper model) {
		// TODO Auto-generated method stub
		model.setCreateTime(Common.getTime1());
		model.setShowTime(Common.getTime());
		model.setTstartTime(Common.getTimeLong(model.getShowStartTime()));
		model.setTendTime(Common.getTimeLong(model.getShowEndTime()));
		this.addT(model);
		return 1;
	}

	/**
	 * 增加一个卷子
	 */
	@Override
	public Sys_TestPaper addTestPaper1(Sys_TestPaper model) {
		// TODO Auto-generated method stub
		model.setCreateTime(Common.getTime1());
		model.setShowTime(Common.getTime());
		model.setTstartTime(Common.getTimeLong(model.getShowStartTime()));
		model.setTendTime(Common.getTimeLong(model.getShowEndTime()));
		this.addT(model);
		return model;
	}
	/**
	 * 查询一个人有试卷
	 */
	@Override
	public Map getTestPaper(Sys_TestPaper model, SysUser sysUser) {
		// TODO Auto-generated method stub
		String hsql = " from Sys_TestPaper t where t.sysUser.table_id = ? ";
		if (null != model && null != model.getName() && !"".equals(model.getName())) {
			hsql += " and t.name like '%" + model.getName() + "%'";
		}
		Object[] obj = new Object[] { sysUser.getTable_id() };
		@SuppressWarnings("unchecked")
		List<Sys_TestPaper> list1 = (List<Sys_TestPaper>) this.getList(hsql, obj, model.getStart(), model.getLimit(), "");
		if (null != list1 && list1.size() > 0) {
			String hql2 = "from Sys_User_TestPaper t where t.sys_TestPaper.table_id = ? ";
			for (int i = 0; i < list1.size(); i++) {
				Sys_TestPaper st = list1.get(i);
				Object[] obj2 = new Object[]{st.getTable_id()};
				List list = this.getList(hql2, obj2, 0, 1000, "");
				list1.get(i).setString1(list.size()+"");
				int count = 0;
				for (int j = 0; j < list.size(); j++) {
					Sys_User_TestPaper sut =(Sys_User_TestPaper)list.get(j);
					if(null == sut.getpValue()){
						continue;
					}else{
						count+=sut.getpValue();
					}
					
				}
			  if(null!=list && list.size()>0){
				  list1.get(i).setString2(count/list.size()+"");
			  }else{
				  list1.get(i).setString2(count+"");
			  }
			}
		}else{
			for (int i = 0; i < list1.size(); i++) {
				list1.get(i).setString1(0+"");
				list1.get(i).setString2(0+"");
			}
		}
		int count = this.getListCount("select count(*) " + hsql, obj, "");
		Map map = new HashMap();
		map.put("count", count % model.getLimit() > 0 ? count / model.getLimit() + 1 : count / model.getLimit());
		map.put("list", list1);
		map.put("sum", count);
		return map;
	}

	/**
	 * 删除试卷
	 * 
	 */
	@Override
	public int deleteTestPaper(String allId) {
		// TODO Auto-generated method stub
		if (null == allId || "".equals(allId)) {
			return 0;
		} else {
			JSONArray jsonarr = JSONArray.fromObject(allId);
			for (int i = 0; i < jsonarr.size(); i++) {
				String table_id = jsonarr.getString(i);
				Sys_TestPaper su = (Sys_TestPaper) this.getT(new Sys_TestPaper(), table_id);
				this.delete(su);
			}
		}
		return 1;
	}

	/**
	 * 修改一个卷
	 */
	@Override
	public int updateTestPaper(Sys_TestPaper model) {
		// TODO Auto-generated method stub
		if (null == model || "".equals(model.getTable_id()) || null == model.getTable_id()) {
			return 0;
		}
		Sys_TestPaper st = (Sys_TestPaper) this.getT(new Sys_TestPaper(), model.getTable_id());
		if (st == null) {
			return 0;
		} else {
			st.setName(model.getName());
			st.setNote(model.getNote());
			st.setShowEndTime(model.getShowEndTime());
			st.setType(model.getType());
			st.setShowStartTime(model.getShowStartTime());
			this.updateT(st);

		}

		return 1;
	}

	/**
	 * 更新一道题的内容
	 */
	@Override
	public int updateTestPaperQuestion(Sys_Question model) {
		// TODO Auto-generated method stub
		if (null == model || "".equals(model.getTable_id()) || null == model.getTable_id()) {
			return 0;
		}
		Sys_Question st = (Sys_Question) this.getT(new Sys_Question(), model.getTable_id());
		if (st == null) {
			return 0;
		} else {
			st.setTitle(model.getTitle());
			st.setContent(model.getContent());
			st.setAnswerTeacher(model.getAnswerTeacher());
			st.setFen(model.getFen());
			st.setType(model.getType());
			this.updateT(st);
		}
		return 1;

	}

	/***
	 * 
	 * 增加一道题的内容
	 *
	 */
	@Override
	public int addTestPaperQuestion(Sys_Question model) {
		// TODO Auto-generated method stub
		model.setCreateTime(Common.getTime1());
		model.setShowTime(Common.getTime());
		this.addT(model);
		return 1;
	}

	/**
	 * 
	 * 查询一张卷中的题
	 * 
	 */
	@Override
	public Map getTestPaperQuestion(Sys_TestPaper model) {
		// TODO Auto-generated method stub
		String hsql = " from Sys_Question t where t.sys_TestPaper.table_id = ? ";
		Object[] obj = new Object[] { model.getTable_id() };
		@SuppressWarnings("unchecked")
		List<SysUser> list1 = (List<SysUser>) this.getList(hsql, obj, 0, 0, "");
		int count = 0;// this.getListCount("select count(*) " + hsql, obj, "");
		Map map = new HashMap();
		map.put("count", count % model.getLimit() > 0 ? count / model.getLimit() + 1 : count / model.getLimit());
		map.put("list", list1);
		map.put("sum", count);
		return map;
	}

	/**
	 * 删除题
	 */
	@Override
	public int deleteQuestion(String allId) {
		// TODO Auto-generated method stub
		if (null == allId || "".equals(allId)) {
			return 0;
		} else {
			JSONArray jsonarr = JSONArray.fromObject(allId);
			for (int i = 0; i < jsonarr.size(); i++) {
				String table_id = jsonarr.getString(i);
				Sys_Question su = (Sys_Question) this.getT(new Sys_Question(), table_id);
				this.delete(su);
			}
		}
		return 1;
	}

	/**
	 * 查询都是当前需要批改的卷
	 */
	@Override
	public Map getHomeWorkChecked(SysUser sysUser) {
		// TODO Auto-generated method stub
		String year = DateTools.getCurrentYear();
		String hql = "select t from Sys_Class t left join t.listsuc t1 where t1.sysUser.table_id = ? and t1.state ='1' and t1.year = '" + year + "'";
		Object[] obj = new Object[] { sysUser.getTable_id() };
		List<Sys_Class> listsc = this.getList(hql, obj, 0, 0, "");
		String str = "";
		if (null != listsc) {
			for (int i = 0; i < listsc.size(); i++) {
				if (i == listsc.size() - 1) {
					str += "'" + listsc.get(i).getTable_id() + "'";
				} else {
					str += "'" + listsc.get(i).getTable_id() + "',";
				}
			}
		} else {
			Map map = new HashMap();
			map.put("count", 0);
			map.put("list", null);
			map.put("sum", 0);
			return map;
		}
		if ("".equals(str)) {
			return null;
		}
		String opt = " t1.table_id, t.tstartTime, t.tendTime,t.showStartTime,t.showEndTime,t.table_id,t.name,t.type,t.state,t1.sysUser.userName,t1.sysUser.table_id,t1.complateTimeShow,t1.state,t1.icCheck,t1.pValue";
		// 这里把这张卷子的人名和人的ID放在String1,和String2里面string3放的是完成时间，strnig4完成状，desc
		// 放的阅卷状态,note中放了卷的table_id
		String hql1 = "from Sys_TestPaper  t  left join t.listsut t1 left join t1.sysUser.listsuc  t2 where t2.sys_Class.table_id in (" + str + ") and t.state ='0' and t.sysUser.table_id = ? ";
		Object[] objc1 = new Object[] { sysUser.getTable_id() };
		List<Sys_TestPaper> list = this.getList("select new com.dream.model.Sys_TestPaper(" + opt + ")" + hql1, objc1, 0, 0, "");
		int count = this.getListCount("select count(*) " + hql1, objc1, "");
		Map map = new HashMap();
		map.put("count", count % sysUser.getLimit() > 0 ? count / sysUser.getLimit() + 1 : count / sysUser.getLimit());
		map.put("list", list);
		map.put("sum", count);
		return map;
	}

	/**
	 * 自动批改
	 */
	@Override
	public int updateAutoCheckTestPaper(JSONArray list) {
		// TODO Auto-generated method stub
		String sql = " from Sys_User_Question t left join t.sys_Question t1 where t1.sys_TestPaper.table_id = ? and t.sysUser.table_id = ? ";
		if (null == list || list.size() <= 0) {
			return 0;
		}
		Object[] obj = null;

		for (int i = 0; i < list.size(); i++) {
			JSONObject jsonObject = list.getJSONObject(i);
			obj = new Object[] { jsonObject.get("juanId"), jsonObject.get("userId") };
			List<Object[]> listuq = this.getList(sql, obj, 0, 0, "");

			int count = 0;
			for (int j = 0; j < listuq.size(); j++) {
				Object[] objuq = listuq.get(j);
				Sys_User_Question suq = null;
				if (objuq.length >= 1 && objuq[0] != null) {
					suq = (Sys_User_Question) objuq[0];
				}
				Sys_Question su = null;
				if (objuq.length >= 2 && objuq[1] != null) {
					su = (Sys_Question) objuq[1];
				}
				if (suq != null && su != null) {
					if ("0".equals(su.getType())) {
						// 主观题
						continue;
					} else {
						if (null == suq.getuAnsouwer() || null == su.getAnswerTeacher()) {
							continue;
						} else {
							if (suq.getuAnsouwer().equals(su.getAnswerTeacher())) {
								suq.setqValue(su.getFen());
								suq.setIsChecked("1");
								this.updateT(suq);// 如果答案相同，给满分
								count += su.getFen();
							} else {
								suq.setIsChecked("1");
								this.updateT(suq);// 如果答案相同，给满分
							}
						}
					}
				}
			}
			String sql1 = "from Sys_User_TestPaper t where t.sys_TestPaper.table_id = ? and t.sysUser.table_id = ?";
			Object[] obj1 = new Object[] { jsonObject.get("juanId"), jsonObject.get("userId") };
			Sys_User_TestPaper sut = (Sys_User_TestPaper) this.getListOne(sql1, obj1, "");
			if (sut == null) {
				throw new RuntimeException();// 如果卷没有，则上面的自动答题不能做数
			} else {
				sut.setpValue(new Long(count));
			}
		}

		return 1;
	}

	/**
	 * 
	 * 查询一个学生现在所有的作业
	 * 
	 * 
	 */
	@Override
	public Map getHomeWorkComplet(JSONArray jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 
	 * 查询学生当前所有的试卷
	 */
	@Override
	public Map getSudentTestPaper(Sys_TestPaper model, SysUser sysUser) {
		String opt = " t1.table_id, t.tstartTime, t.tendTime,t.showStartTime,t.showEndTime,t.table_id,t.name,t.type,t.state,t1.sysUser.userName,t1.sysUser.table_id,t1.complateTimeShow,t1.state,t1.icCheck,t1.pValue";
		// 这里把这张卷子的人名和人的ID放在String1,和String2里面string3放的是完成时间，strnig4完成状，desc
		// 放的阅卷状态,note中放了卷的table_id
		// String hql1 =
		// "from Sys_TestPaper  t  left join t.listsut t1 left join t1.sysUser.listsuc  t2 where t2.sys_Class.table_id in ("
		// + str + ") and t.state ='0' and t.sysUser.table_id = ? ";
		String hsql = " from Sys_TestPaper t left join t.listsut t1  where t1.sysUser.table_id = ? ";
		Object[] obj = new Object[] { sysUser.getTable_id() };
		@SuppressWarnings("unchecked")
		List<SysUser> list1 = (List<SysUser>) this.getList("select new com.dream.model.Sys_TestPaper(" + opt + ")" + hsql, obj, model.getStart(), model.getLimit(), "");
		int count = this.getListCount("select count(*) " + hsql, obj, "");
		Map map = new HashMap();
		map.put("count", count % model.getLimit() > 0 ? count / model.getLimit() + 1 : count / model.getLimit());
		map.put("list", list1);
		map.put("sum", count);
		return map;
	}

	/**
	 * 
	 * 得到一张卷中的详细信息，并进行答题
	 */
	@Override
	public Map getTest_PaperQuestionInfo(Sys_TestPaper model, SysUser sysUser) {
		// String opt =
		// " t1.table_id, t.tstartTime, t.tendTime,t.showStartTime,t.showEndTime,t.table_id,t.name,t.type,t.state,t1.sysUser.userName,t1.sysUser.table_id,t1.complateTimeShow,t1.state,t1.icCheck,t1.pValue";
		// 这里把这张卷子的人名和人的ID放在String1,和String2里面string3放的是完成时间，strnig4完成状，desc
		// 放的阅卷状态,note中放了卷的table_id
		// String hql1 =
		// "from Sys_TestPaper  t  left join t.listsut t1 left join t1.sysUser.listsuc  t2 where t2.sys_Class.table_id in ("
		// + str + ") and t.state ='0' and t.sysUser.table_id = ? ";
		// String opt =
		// "t.table_id, t.completeTime, t.type, t.timeStundent, t.timeStundent1, t.title, t.content, t.fen, t.answerTeacher, t.qtype, t.qaType,t1.uAnsouwer";
		String hsql = " from Sys_Question t where t.sys_TestPaper.table_id = ? ";
		Object[] obj = new Object[] { model.getTable_id() };

		@SuppressWarnings("unchecked")
		// "select new com.dream.model.Sys_Question(" + opt + ")"
		List<Sys_Question> list1 = (List<Sys_Question>) this.getList(hsql, obj, model.getStart(), model.getLimit(), "");
		if (hsql != null) {

			String sql = "from Sys_User_Question t where t.sysUser.table_id = ? and t.sys_Question.table_id = ? ";
			Object[] obj1 = null;
			for (int i = 0; i < list1.size(); i++) {
				obj1 = new Object[] { sysUser.getTable_id(), list1.get(i).getTable_id() };
				Sys_User_Question suq = (Sys_User_Question) this.getListOne(sql, obj1, "");
				if (suq != null) {
					list1.get(i).setString1(suq.getuAnsouwer());
					list1.get(i).setString2(suq.getIsChecked());
					list1.get(i).setString3(suq.getqValue() + "");
				}
			}
		}
		int count = this.getListCount("select count(*) " + hsql, obj, "");
		Map map = new HashMap();
		map.put("count", count % model.getLimit() > 0 ? count / model.getLimit() + 1 : count / model.getLimit());
		map.put("list", list1);
		map.put("sum", count);
		return map;

	}

	/**
	 * 
	 * 回答一首题，
	 */
	@Override
	public int updateQuestionValue(Sys_Question model, SysUser sysUser, String value) {
		// TODO Auto-generated method stub
		String hql = "from Sys_User_Question t where t.sysUser.table_id = ? and t.sys_Question.table_id = ?";

		Object[] obj = new Object[] { sysUser.getTable_id(), model.getTable_id() };

		Sys_User_Question su = (Sys_User_Question) this.getListOne(hql, obj, "");
		// 如果没有，就表示没有答过，需要增加
		if (null == su) {
			Sys_User_Question su1 = new Sys_User_Question();
			su1.setqValue(0);// 无分
			su1.setQtype(model.getType());// 类型是文字
			su1.setScompleteTime(model.getCompleteTime());
			su1.setuAnsouwer(value);
			su1.setSysUser(sysUser);
			su1.setSys_Question(model);
			this.addT(su1);
			return 1;
		}
		su.setqValue(0);// 无分
		su.setQtype(model.getType());// 类型是文字
		su.setScompleteTime(model.getCompleteTime());
		su.setuAnsouwer(value);
		this.updateT(su);
		return 1;
	}

	/**
	 * 
	 * 
	 * 完成学生的一个卷,都是完成他的批改
	 * 
	 * 
	 */
	@Override
	public int updateCompletTestPaper(SysUser sysUser, String juanId) {
		// TODO Auto-generated method stub
		String sql = "from Sys_User_TestPaper  t where t.sys_TestPaper.table_id = ? and t.sysUser.table_id = ?";
		Object[] obj = new Object[] { juanId, sysUser.getTable_id() };
		Sys_User_TestPaper sut = (Sys_User_TestPaper) this.getListOne(sql, obj, "");
		if ("2".equals(sysUser.getUserType()) || "5".equals(sysUser.getUserType())) {
			if (null != sut) {
				sut.setIcCheck("1");
				this.updateT(sut);
			}
			return 1;
		}
		if (null != sut) {
			sut.setState("1");
			this.updateT(sut);
		}
		return 1;
	}

	/**
	 * 
	 * 
	 * 都是给一道 题 打分
	 */
	@Override
	public int updateQuestionQValue(Sys_Question model, SysUser sysUser, String qValue) {
		// TODO Auto-generated method stub
		String hql = "from Sys_User_Question t where t.sysUser.table_id = ? and t.sys_Question.table_id = ?";
		Object[] obj = new Object[] { sysUser.getTable_id(), model.getTable_id() };
		Sys_User_Question su = (Sys_User_Question) this.getListOne(hql, obj, "");
		// 如果没有
		if (null == su) {
			return 0;
		}
		su.setqValue(Integer.parseInt(qValue));// 打分
		this.updateT(su);
		return 1;
	}

	@Override
	public int updateTeacherCompletTestPaper(SysUser sysUser1, String juanId) {
		// TODO Auto-generated method stub
		String sql = "from Sys_User_TestPaper  t where t.sys_TestPaper.table_id = ? and t.sysUser.table_id = ?";
		Object[] obj = new Object[] { juanId, sysUser1.getTable_id() };
		Sys_User_TestPaper sut = (Sys_User_TestPaper) this.getListOne(sql, obj, "");
		if (null != sut) {
			sut.setIcCheck("1");
			this.updateT(sut);
		}
		String sql1 = "select t from Sys_User_Question t left join t.sys_Question t1 where t1.sys_TestPaper.table_id = ? and t.sysUser.table_id = ? ";
		Object[] obj1 = new Object[] { juanId, sysUser1.getTable_id() };

		List<Sys_User_Question> squlist = this.getList(sql1, obj1, 0, 0, "");

		if (null != squlist) {
			Long coun = new Long(0);
			for (int i = 0; i < squlist.size(); i++) {
				coun += squlist.get(i).getqValue();
			}
			sut.setpValue(coun);
		}
		this.updateT(sut);
		return 1;
	}

	/**
	 * 
	 * 查询按pID查询学校
	 * 
	 */
	@Override
	public Map getListLv(String str) {
		// TODO Auto-generated method stub
		Map map = new HashMap();
		String hql = "froom Sys_Class t where t.cpid = ? ";
		Object[] obj = new Object[] { str };
		List list1 = this.getList(hql, obj, 0, 1000, "");
		map.put("count", list1.size());
		map.put("list", list1);
		map.put("sum", list1.size());
		return map;
	}

	@Override
	public Sys_Question addTestPaperQuestion1(Sys_Question model) {
		// TODO Auto-generated method stub
		model.setCreateTime(Common.getTime1());
		model.setShowTime(Common.getTime());
		this.addT(model);
		return model;
	}
}
